package com.bao.shop.service.impl;

import com.bao.shop.entity.Cart;
import com.bao.shop.entity.Goods;
import com.bao.shop.entity.User;
import com.bao.shop.service.CartService;
import com.bao.shop.service.GoodsService;

import java.math.BigDecimal;
import java.util.ArrayList;

/**
 * @author baoye
 * @date 2024-07-25/19:33
 */
public class CartServiceImpl implements CartService {
    static {
        CARTS.add(new Cart("55",new ArrayList<>()));
    }
    @Override
    public void addCart(User user) {
        CARTS.add(new Cart(user.getUserName(),new ArrayList<>()));
    }

    @Override
    public Cart findCart(User user) {
        for (Cart cart : CARTS) {
            if(cart.getUserName().equals(user.getUserName())){
                return cart;
            }
        }
        return null;
    }

    @Override
    public void addGoodsToCart(User user, Goods goods,Integer num) {
        Cart cart=findCart(user);
        //遍历集合,找到名字一样的直接加
        for (Goods forGoods : cart.getGoodsList()) {
            if(forGoods.getGoodsId().equals(goods.getGoodsId())){
                forGoods.setStock(forGoods.getStock()+num);
                return;
            }
        }
        cart.getGoodsList().add(new Goods(goods.getGoodsId(), goods.getName(), goods.getPrice(),num));



    }

    @Override
    public void printCart(User user) {
        Cart cart=findCart(user);
        for (Goods goods : cart.getGoodsList()) {
            System.out.println(goods);
        }
    }

    @Override
    public void pay(User user) {
        Cart cart=findCart(user);
        if(cart.getGoodsList().size()<=0){
            System.out.println("购物车中还没有商品!");
            return;
        }
        printCart(user);
        BigDecimal temp=new BigDecimal(0);
        for(Goods goods:cart.getGoodsList()){
             temp=temp.add(goods.getPrice().multiply(new BigDecimal(goods.getStock())));
        }
        temp=temp.divide(new BigDecimal(1),BigDecimal.ROUND_HALF_UP);//保留两位小数,四舍五入
        System.out.print("总价:"+temp);
        System.out.print("是否购买(Y/N):");
        if(!"y".equalsIgnoreCase(INPUT.next())){
            return;
        }
        System.out.print("请输入价格:");
        BigDecimal price=new BigDecimal(INPUT.next());
        if(price.compareTo(temp) < 0){
            System.out.println("钱不够!");
        }
        else{
            System.out.println("购买成功,还剩"+price.subtract(temp)+"元!");
            cart.getGoodsList().removeAll(cart.getGoodsList());
        }
    }
}
